/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 18-10-9
 * Time: 上午11:28
 * Description: storage
 */
const storage = window.localStorage;
const constants = require('../utils/constants.js').default;

/**
 * 获取缓存数据
 * @param key
 * @returns {string}
 */
export function getStorage(key) {
  return storage.getItem(key);
}

/**
 * 存入数据
 * @param key key
 * @param value value
 * @returns {string}
 */
export function putStorage(key, value) {
  storage.setItem(key, value);
}

/**
 * 存cookies
 * @param name key
 * @param value value
 * @param time 时间
 */
export function setCookies(name, value, time) {
  let d = new Date();
  if (!time)
    d.setTime(d.getTime() + constants.sessionExpire);
  else
    d.setTime(d.getTime() + time);
  let expires = "expires=" + d.toUTCString();
  document.cookie = name + "=" + value + "; " + expires;
}

/**
 * 取cookies
 * @param name key
 */
export function getCookies(name) {
  let key = name + "=";
  let ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1);
    if (c.indexOf(key) !== -1) {
      let res = c.substring(key.length, c.length);
      //重置失效时间
      setCookies(name, res);
      return c.substring(key.length, c.length);
    }
  }
  return "";
}

/**
 * 清理cookies
 * @param key key
 */
export function clearCookies(key) {
  setCookies(key, '', -1)
}

